package com.lagou.springbootjob.controller;

import com.lagou.springbootjob.bean.BlogArticle;
import com.lagou.springbootjob.service.BlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Calendar;

@Controller
public class IndexController {

    @Autowired
    private BlogService blogService;

    @RequestMapping("index")
    public String index(Model model){

        int curPageIndex = 0;
        int previousPageIndex = curPageIndex - 1;
        int nextPageIndex = curPageIndex + 1;

        Sort sort = Sort.by(Sort.Direction.DESC, "created");
        Pageable pageable = PageRequest.of(0,3, sort);

        Page<BlogArticle> articlePage = blogService.findAll(pageable);


        int lastPageIndex = articlePage.getTotalPages()-1;

        model.addAttribute("curPageIndex", curPageIndex);
        model.addAttribute("previousPageIndex", previousPageIndex);
        model.addAttribute("nextPageIndex", nextPageIndex);
        model.addAttribute("lastPageIndex", lastPageIndex);
        model.addAttribute("articleList", articlePage.getContent());

        System.out.println(curPageIndex + "\t" + previousPageIndex + "\t" + nextPageIndex + "\t" + lastPageIndex + "\t" + articlePage.getTotalPages());
        for (BlogArticle article : articlePage.getContent()) {
            System.out.println(article);
        }

        model.addAttribute("currentYear", Calendar.getInstance().get(Calendar.YEAR));
        return "client/index";
    }
}
